// 开始练习API
import { NextRequest } from 'next/server';
import { SessionDB } from '@/lib/mysql';
import { getCurrentUser, getTokenFromHeader, ApiResponse } from '@/lib/auth';

// 开始新的练习会话
export async function POST(request: NextRequest) {
  try {
    // 验证用户登录 - 从Authorization header获取token
    const authHeader = request.headers.get('Authorization');
    const token = getTokenFromHeader(authHeader || '');
    const currentUser = getCurrentUser(token || undefined);
    if (!currentUser) {
      return ApiResponse.unauthorized('请先登录');
    }

    // 解析请求体
    const body = await request.json();
    const { topicId, topicName, questionCount, difficultyRange } = body;

    // 验证必填字段
    if (!topicId || !topicName || !questionCount) {
      return ApiResponse.error('缺少必填字段');
    }

    // 创建练习会话
    const sessionId = await SessionDB.create(
      currentUser.userId,
      topicId,
      topicName,
      questionCount,
      difficultyRange || '1,2,3,4,5'
    );

    return ApiResponse.success(
      {
        sessionId,
        topicId,
        topicName,
        questionCount,
        difficultyRange,
      },
      '练习会话创建成功'
    );
  } catch (error) {
    console.error('创建练习会话错误:', error);
    return ApiResponse.serverError('创建练习会话失败');
  }
}
